﻿using Amap.WebApi;
using Bigway.Common.Models;
using Bigway.Common.Models.DtoModels;
using System.Text.Json;
using Bigway.Common.Utils;

namespace Bigway.Common.Services;

public class GeoDecoder(IGeoService geoService): IGeoDecoder
{
    public async Task<Coordinate?> DecodeAddressAsync(string address, CancellationToken token = default)
    {
        var jsonResponse = await geoService.GetGeoAsync(address);
        if (jsonResponse is null or "" or "null" or "{}")
            return null;
        try
        {
            var response = JsonSerializer.Deserialize<SimpleGeoDecodeResponseDto>(jsonResponse, CommonStatics.DefaultJsonOptions)!;
            if (response.Info != "OK")
                return null;

            return response.Geocodes.Length > 0 
                ? response.Geocodes[0].Location.ParseAsCoordinate() 
                : null;
        }
        catch (Exception)
        {
            return null;
        }
    }
}